/*
 * JimBot Manager - Mobile Manager for Java IM Bot
 * Copyright (C) 2013  Aleksandr Krysin (alex_xpert)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ru.worldjb.jimbot_manager;

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;

/**
 * @author alex_xpert
 */
public class JimBotManager extends MIDlet {
    private boolean midletPaused = false;
    private String HOST_AND_PORT = "";
    private String LOGIN = "";
    private String PASSWORD = "";
//    private RecordStore rs = null;

    /**
     * The JimBotManager constructor.
     */
    public JimBotManager() {
    }

    /**
     * Initializes the application. It is called only once when the MIDlet is
     * started. The method is called before the
     * <code>startMIDlet</code> method.
     */
    private void initialize() {
        
    }

    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {
        switchDisplayable(null, getForm());
    }

    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {
    }

    /**
     * Switches a current displayable in a display. The
     * <code>display</code> instance is taken from
     * <code>getDisplay</code> method. This method is used by all actions in the
     * design for switching displayable.
     *
     * @param alert the Alert which is temporarily set to the display;
     * if <code>null</code>, then <code>nextDisplayable</code> is set
     * immediately
     * @param nextDisplayable the Displayable to be set
     */
    private void switchDisplayable(Alert alert, Displayable nextDisplayable) {
        if(nextDisplayable == null) return;
        Display display = getDisplay();
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }
    }

/**
     * Returns a display instance.
     *
     * @return the display instance.
     */
    private Display getDisplay() {
        return Display.getDisplay(this);
        
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable(null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started. Checks whether the MIDlet have been
     * already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet();
        } else {
            initialize();
            startMIDlet();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     *
     * @param unconditional if true, then the MIDlet has to be unconditionally
     * terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }
    
    private Form getForm() {
//        String[] stores = RecordStore.listRecordStores();
//        if(stores != null && stores.length > 0) {
//            try {
//                rs = RecordStore.openRecordStore(stores[0], false);
//                HOST_AND_PORT = rs.getRecord(1) == null ? "" : new String(rs.getRecord(1));
//                LOGIN = rs.getRecord(2) == null ? "" : new String(rs.getRecord(2));
//                PASSWORD = rs.getRecord(3) == null ? "" : new String(rs.getRecord(3));
//            } catch(Exception ex) {
//                ex.printStackTrace();
//            }
//        }
        final Form f = new Form("JimBot Manager");
        f.append("Соединение с сервером JimBot");
        f.append(new TextField("IP сервера и порт", HOST_AND_PORT, 25, TextField.URL));
        f.append(new TextField("Логин", LOGIN, 25, TextField.PLAIN));
        f.append(new TextField("Пароль", PASSWORD, 25, TextField.PASSWORD));
        f.append(new StringItem("", ""));
        f.addCommand(new Command("OK", Command.OK, 0));
        f.setCommandListener(new CommandListener() {

            public void commandAction(Command cmnd, Displayable dsplbl) {
                 if(cmnd.getCommandType() == Command.OK) {
//                     if(rs != null) {
//                         try {
//                            rs.setRecord(1, ((TextField) ((Form) dsplbl).get(1)).getString().getBytes(), 0, 0);
//                            rs.setRecord(2, ((TextField) ((Form) dsplbl).get(2)).getString().getBytes(), 0, 0);
//                            rs.setRecord(3, ((TextField) ((Form) dsplbl).get(3)).getString().getBytes(), 0, 0);
//                         } catch(Exception ex) {
//                             ex.printStackTrace();
//                         }
//                     } else {
//                         try {
//                            rs = RecordStore.openRecordStore("jimbot_manager", true);
//                            HOST_AND_PORT = ((TextField) ((Form) dsplbl).get(1)).getString();
//                            LOGIN = ((TextField) ((Form) dsplbl).get(2)).getString();
//                            PASSWORD = ((TextField) ((Form) dsplbl).get(3)).getString();
//                            rs.addRecord(HOST_AND_PORT.getBytes(), 0, 0);
//                            rs.addRecord(LOGIN.getBytes(), 0, 0);
//                            rs.addRecord(PASSWORD.getBytes(), 0, 0);
//                            rs.closeRecordStore();
//                        } catch(Exception ex) {
//                            ex.printStackTrace();
//                        }
//                     }
                     getMainProps(dsplbl);
                 }
            }
        });
        return f; 
    }
    
    /**
     * Get MainProps
     */
    private void getMainProps(Displayable d) {
        final Form f = (Form) d;
        String ip = ((TextField) f.get(1)).getString(), 
                login = ((TextField) f.get(2)).getString(), 
                password = ((TextField) f.get(3)).getString();
        if(ip.equals("") || login.equals("") || password.equals("")) {
            switchDisplayable(null, f);
            ((StringItem) f.get(4)).setText("Одно или несколько полей не заполнены!");
            return;
        }
        try {
            HttpConnection con = (HttpConnection) Connector.open("http://" + ((TextField) f.get(1)).getString() + "/api?page=login&name=" + ((TextField) f.get(2)).getString() + "&password=" + ((TextField) f.get(3)).getString());
            InputStreamReader reader = new InputStreamReader(con.openInputStream(), "UTF-8");
            StringBuffer sb = new StringBuffer();
            int b;
            while((b = reader.read()) != -1) {
                sb.append((char) b);
            }
            reader.close();
            final String uid = con.getRequestProperty("uid");
            con.close();
            Form form = new Form("Основные настройки");
            final String[] props = split(sb.toString(), "|", 0);
            for(int i=0;i<props.length;i++) {
                String[] p = split(props[i], ";", 0);
                form.append(new TextField(p[1], p[2], 25, TextField.ANY));
            }
            form.addCommand(new Command("Сохранить", Command.ITEM, 0));
            form.setCommandListener(new CommandListener() {

                public void commandAction(Command cmnd, Displayable dsplbl) {
                     if(cmnd.getCommandType() == Command.ITEM) {
                         try {
                            StringBuffer data = new StringBuffer();
                            boolean first = true;
                            for(int i=0;i<props.length;i++) {
                                String[] p = split(props[i], ";", 0);
                                if(!first) {
                                    data.append("|");
                                } else {
                                    first = false;
                                }
                                data.append(p[0] + ";" + p[2]);
                            }
                            HttpConnection con = (HttpConnection) Connector.open("http://" + ((TextField) f.get(1)).getString() + "/api?page=setMainProps&name=" + ((TextField) f.get(2)).getString() + "&password=" + ((TextField) f.get(3)).getString());
                            con.setRequestMethod("POST");
                            OutputStreamWriter writer = new OutputStreamWriter(con.openOutputStream());
                            writer.write(data.toString());
                            writer.write("&");
                            writer.flush();
                            writer.close();
                            con.close();
                         } catch(Exception ex) {
                             ex.printStackTrace();
                         }
                     }
                }
            });
            switchDisplayable(null, form);
        } catch(Exception ex) {
            ((StringItem) f.get(4)).setText(ex.toString());
            switchDisplayable(null, f);
        }
    }
    
    /**
     * Так как в Java ME нет String.split(), то описываем сей метод...
     * @param original
     * @param separator
     * @param count
     * @return 
     */
    private String[] split(String original, String separator, int count) {
        String[] result;
        int index = original.indexOf(separator);
        if(index >= 0)
            result = split(original.substring(index + separator.length()), separator, count + 1);
        else {
            result = new String[count + 1];
            index = original.length();
        }
        result[count] = original.substring(0, index);
        return result;
    }

}
